/**
 * step4 发布广告
 */
define(['../../common/service', '../../model/data', './createAdUtils', '../../plugins/pretag'],
    function(http, Data, Util) {
        var Step4 = {
            cache: Util.publishParamCache,
            init: function() {
                var self = this;
                //注册 按钮
                self._event();
            },
            _event: function() {
                var self = this;
                //publish check
                $("button.ad-publish").unbind("click").click(function() {
                    self._publish();
                });
            }
            //发布广告
            ,
            _publish: function() {
                    //获取bid
                    var self = this;
                    self.getNameConfigValues();
                    self.getBidInfoValues();
                    self.getCreativeValues();
                    self.cache.ecTemplateMaterielId = $("#originality .img li").eq(1).find(".thumbnail>img").attr('data-templateId');
                    //self.cache.customAudiences = $(".customaudience").select2("data");
                    //发布
                    if (!self._publishCheck()) {
                        return;
                    }
                    //构造受众参数
                    if (self.cache.userAudienceId == -1){
                        //需要创建新的受众
                        self.cache.audience = {
                            name : $.trim($("#audience").find('input[name="audience-name"]').val()),
                            fbTargeting : Util.audienceCache.fbTargeting,
                            localTargeting : Util.audienceCache.localTargeting,
                            potentialUser : Util.audienceCache.potentialUser,
                            productCatalogId : $("div.ndp-drop-wrapper[name=productSet-drop]").drop("data").fb_ids[0].catalog_id
                        }
                        if (Util.audienceCache.produceSetId){
                            self.cache.audience.productSetId = Util.audienceCache.produceSetId;
                        }
                    } else {
                        if ($('input[name="cross-selling"]').prop("checked")){
                            self.cache.audience = {
                                productSetId : $("div.ndp-drop-wrapper[name=audience-product-set-drop]").data("val")
                            }
                        } else {
                            self.cache.audience = null;
                        }
                    }

                    console.log(self.cache);
                    $("button.ad-publish").unbind("click");
                    $("button.ad-publish").css("background-color",'#d9e0e3');
                    $("button.ad-publish").css("border-color",'#d9e0e3');
                    http.work('/publishbatchs/ecPublish', self.cache, 'POST').then(function(res) {
                        if (res.flag == 'fail') {
                            if (res.errorCode == "60136"){
                                //受众名称存在
                                Kit.warning5($('div.fmp-article'), 600, $("#audience").find('input[name="audience-name"]'));
                            }

                            Kit.alert2(res.errorMsg);
                            //重新bind publish btn
                            self._event();
                            $("button.ad-publish").css("background-color",'#fc7408');
                            $("button.ad-publish").css("border-color",'#fc7408');
                            return;
                        } else {
                            window.location.hash = "#!adList";
                        }
                    });
                }
                /**
                 * 获取广告名称 values
                 */
                ,
            getNameConfigValues: function() {
                    var self = this;
                    self.cache.campaignName = superInput.getData($("div[super-input-warp='adCampSeq']"));
                    self.cache.adSetName = superInput.getData($("div[super-input-warp='adSetSeq']"));
                    self.cache.adName = superInput.getData($("div[super-input-warp='adGroupSeq']"));
                    window.localStorage.setItem("adGroupSeq", JSON.stringify(self.cache.adName));
                    window.localStorage.setItem("adSetSeq", JSON.stringify(self.cache.adSetName));
                    window.localStorage.setItem("adCampSeq", JSON.stringify(self.cache.campaignName));
                }
                /**
                 * 获取 预算出价
                 */
                ,
            getBidInfoValues: function() {
                var self = this;
                self.cache.bidInfo = {
                        billingEvent: $("input[name=charge]").attr('data-val'),
                        customEventType: $("input[name=activeType]").attr('data-val'),
                        budgetType: $("input[name=budget]").attr('data-val'),
                        isAutoBid: $("input[type=radio][name=price]:checked").val(),
                        optimizationGoal: $("input[name=optimizing]").attr('data-val'),
                    }
                    //获取排期
                if ($("input[name=schedule]").attr('data-val') == 0) { //周期
                    self.cache.bidInfo.startTime = $('input[class=daterangepicker-sample3]').val(); //2016-05-03 15:12:00
                } else {
                    var tempDate = $('input[class=daterangepicker-sample3]').val().split(' - ');
                    self.cache.bidInfo.startTime = tempDate[0];
                    self.cache.bidInfo.endTime = tempDate[1];
                }
                //获取预算
                if (self.cache.bidInfo.budgetType == "0") {
                    self.cache.bidInfo.dailyBudget = Number($("input.budget-input").val() * 100).toFixed(0);
                } else {
                    self.cache.bidInfo.lifetimeBudget = Number($("input.budget-input").val() * 100).toFixed(0);
                }
                //获取单价
                if (self.cache.bidInfo.isAutoBid == "false") {
                    self.cache.bidInfo.bidAmount = Number($("input.price-input").val() * 100).toFixed(0);
                }
            },
            getCreativeValues: function() {
                var self = this;
                self.cache.creative = {
                    callToActionType: $("input[name=originality]").attr('data-val'),
                    chooseType: $("input[type=radio][name=pic]:checked").val(),
                    pageId: $("select[name=homepage-select2]").val(),
                    link: $("input[name=link]").val(),
                    linkCaption: $("input[name=linkCaption]").val(), //显示网址
                    dynamicMsgLinkDesc: Util.fieldObj.dynamicMsgLinkDesc.getContent(), //动态消息链接描述
                    linkParam: $("input[name=linkParam]").val() //网址参数
                }
                if ($("input#video-ad-extend:checked").length == 0) {
                    self.cache.creative.multiShareEndCard = false;
                } else {
                    self.cache.creative.multiShareEndCard = true;
                }
                self.cache.creative.adTitle = Util.fieldObj.dpaTitle.getContent();
                self.cache.creative.adWord = Util.fieldObj.dpaAdword.getContent();

                window.localStorage.setItem('linkParam', self.cache.creative.linkParam);
            },
            _publishCheck: function() {
                var self = this;



                //判断输入是否为空,我们就按照从上到下的顺序来吧^_^
                //顺序：受众，预算，单价，创意模板，网页，标题,广告语
                //受众
                if (!checkAudience()){
                    return false;
                }
                function checkAudience(){
                    var _audience = $('div.ndp-drop-wrapper[name="audience-drop"]').drop("data");
                    if (_audience.id == -1){
                        //新受众 需要判断受众是否生成
                        if (!Util.audienceCache.fbTargeting || !Util.audienceCache.isSuccess){
                                Kit.warning5($('div.fmp-article'), 600, $(".btn-generate-audience", "#audience"));
                                return false;
                        } else {
                            //如果受众已经生成 需要判断名称是否填写
                            var audienceNameV = $.trim($("#audience").find('input[name="audience-name"]').val());
                            if (audienceNameV == ''){
                                Kit.warning5($('div.fmp-article'), 600, $("#audience").find('input[name="audience-name"]'));
                                return false;
                            }
                        }

                        //如果受众已经生成 需要判断名称是否填写
                        var audienceNameV = $.trim($("#audience").find('input[name="audience-name"]').val());
                        if (audienceNameV == ''){
                            Kit.warning5($('div.fmp-article'), 600, $("#audience").find('input[name="audience-name"]'));
                            return false;
                        }
                    } else {
                        if (!Util.audienceCache.isSuccess){
                            Kit.warning5($('div.fmp-article'), 600, $(".btn-audience-edit", "#audience"));
                            return false;
                        }
                    }

                    return true;
                }

                if (Kit.warningIsBlank(self.cache.userAudienceId,
                       $('div[name=audience-drop]'), $('div.fmp-article'), 500)) {
                   return false;
                }
                if (self.cache.bidInfo.budgetType == 0 && Number(self.cache.bidInfo.dailyBudget) < 500) {
                    Kit.warning5($('div.fmp-article'), 600, $("input.budget-input"));
                    return false;
                } else if (Number(self.cache.bidInfo.lifetimeBudget) < 500) {
                    Kit.warning5($('div.fmp-article'), 600, $("input.budget-input"));
                    return false;
                }
                //获取单价
                if (self.cache.bidInfo.isAutoBid == "false" && Number(self.cache.bidInfo.bidAmount) < 1) {
                    Kit.warning5($('div.fmp-article'), 600, $("input.price-input"));
                    return false;
                } else if (Kit.warningIsBlank(self.cache.ecTemplateMaterielId, $("#originality .img li").eq(0), $('div.fmp-article'), 900)) {
                    return false;
                } else if (Kit.warningIsBlank(self.cache.creative.link, $('input[name=link]'), $('div.fmp-article'), 1200)) {
                    return false;
                } else if (Kit.warningIsBlank($.trim(self.cache.creative.adTitle), $('div[name=dpa-title-wrapper]>div:first-child'),
                        $('div.fmp-article'), 1200)) {
                    return false;
                } else if (Kit.warningIsBlank($.trim(self.cache.creative.adWord), $('div[name=dpa-adword-wrapper]>div:first-child'),
                        $('div.fmp-article'), 1300)) {
                    return false;
                } else if (Kit.warningIsBlank(self.cache.campaignName, $('div[super-input-warp=adCampSeq]>div:first-child'),
                        $('div.fmp-article'), 1500)) {
                    return false;
                } else if (Kit.warningIsBlank(self.cache.adSetName, $('div[super-input-warp=adSetSeq]>div:first-child'),
                        $('div.fmp-article'), 1500)) {
                    return false;
                } else if (Kit.warningIsBlank(self.cache.adName, $('div[super-input-warp=adGroupSeq]>div:first-child'),
                        $('div.fmp-article'), 1500)) {
                    return false;
                }

                return true;

            }
        };
        return Step4;
    });
